<script lang="ts" setup>
import {
  ElMessageBox,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElTabs,
  ElTabPane,
  ElRadioGroup,
  ElRadio,
  ElIcon,
  ElSlider,
  ElDivider,
  ElDialog,
  ElMenu,
  ElMenuItem,
  ElMessage,
} from 'element-plus';
import { reactive, ref, onMounted } from 'vue';
import { router } from '#/router';
import {
  setAlarmReceptionSetting,
  getAlarmReceptionSetting,
} from '#/api/sys/alarm';
import { useDebounceFn } from "@vueuse/core";

const activeName = ref('first');
const ruleFormRef = ref();
const ruleForm = reactive<RuleForm>({
  defaultFlyHeight: 0,
  defaultFlySpeed: 0,
  defaultTurnBackHeight: 0,
  autoTreatTheCasesStatus: '1',
  warningInstanceExpire: 0,
  addReachTargetPointActions: [],
});

const rules = reactive({});
const submitForm = async () => {
  ruleForm.addReachTargetPointActions = actionItems.value;
  try {
    await ruleFormRef.value?.validate();
    const params = {
      defaultFlyHeight: ruleForm.defaultFlyHeight,
      defaultFlySpeed: ruleForm.defaultFlySpeed,
      defaultTurnBackHeight: ruleForm.defaultTurnBackHeight,
      autoTreatTheCasesStatus: ruleForm.autoTreatTheCasesStatus,
      warningInstanceExpire: ruleForm.warningInstanceExpire,
      addReachTargetPointActions: ruleForm.addReachTargetPointActions,
    };
    const { code, message = '配置失败' } =
      await setAlarmReceptionSetting(params);
    if (code !== 200) throw new Error(message);
    ElMessage.success('配置成功');
    getAlarm();
  } catch (err) {
    ElMessage.error("操作失败");
  }
};

const debouncedSubmitForm = useDebounceFn(submitForm, 500);

const resetForm = (formEl) => {
  if (!formEl) return;
  ruleFormRef.value.resetFields();
};

// 动作列表数据
const actionItems = ref([]);
let counter = 0;

// 添加动作
// 动作类型(1悬停,2无人机偏航角,3云台俯仰角,拍照,5全景拍照,6开始录像,7相机变焦,8停止录像,9开始等距间隔拍照,10开始等时间隔拍照，11结束间隔拍照)
const settingList = [
  {
    actionType: 1,
    name: '悬停',
    // 时长 1-900s
  },
  {
    actionType: 2,
    name: '无人机偏航角',
    // -180°到180°
  },
  {
    actionType: 3,
    name: '云台俯仰角',
    // -120°到 45°
  },
  {
    actionType: 4,
    name: '拍照',
  },
  {
    actionType: 5,
    name: '全景拍照',
  },
  {
    actionType: 6,
    name: '开始录像',
  },
  {
    actionType: 7,
    name: '相机变焦',
    // 2X-200X
  },
  {
    actionType: 8,
    name: '停止录像',
  },
  {
    actionType: 9,
    name: '开始等距间隔拍照',
  },
  {
    actionType: 10,
    name: '开始等时间隔拍照',
    // 1-30s
  },
  {
    actionType: 11,
    name: '结束间隔拍照',
  },
];
const actionMin = ref(0);
const actionMax = ref(0);

const dialogVisible = ref(false);

// 添加动作
const addAction = () => {
  // 弹窗选择动作类型
  dialogVisible.value = true;
};

// 已选择动作
const selectAction = (item) => {
  // 设置最大最小值
  switch (item.actionType) {
    case 1:
      actionMin.value = 1;
      actionMax.value = 900;
      break;
    case 2:
      actionMin.value = -180;
      actionMax.value = 180;
      break;
    case 3:
      actionMin.value = -120;
      actionMax.value = 45;
      break;
    case 7:
      actionMin.value = 2;
      actionMax.value = 200;
      break;
    case 10:
      actionMin.value = 1;
      actionMax.value = 30;
      break;
  }
  actionItems.value.push({
    name: item.name,
    actionType: item.actionType,
    actionValue: 0,
    actionMin: actionMin.value,
    actionMax: actionMax.value,
  });
  dialogVisible.value = false;
};

// 删除动作
const removeAction = (index) => {
  actionItems.value.splice(index, 1);
};

const del = (item) => {
  item.actionValue -= 1;
  if (item.actionValue <= item.actionMin) {
    item.actionValue = item.actionMin;
  }
};

const add = (item) => {
  item.actionValue += 1;
  if (item.actionValue >= item.actionMax) {
    item.actionValue = item.actionMax;
  }
};

const changeValue = (item) => {
  if (item.actionValue <= item.actionMin) {
    item.actionValue = item.actionMin;
  }
  if (item.actionValue >= item.actionMax) {
    item.actionValue = item.actionMax;
  }
};

const getAlarm = async () => {
  try {
    const { data } = await getAlarmReceptionSetting();
    ruleForm.defaultFlyHeight = data.defaultFlyHeight;
    ruleForm.defaultFlySpeed = data.defaultFlySpeed;
    ruleForm.defaultTurnBackHeight = data.defaultTurnBackHeight;
    ruleForm.autoTreatTheCasesStatus = data.autoTreatTheCasesStatus + '';
    ruleForm.warningInstanceExpire = data.warningInstanceExpire;

    if (data.getReachTargetPointActions.length > 0) {
      data.getReachTargetPointActions.forEach((item) => {
        item.actionValue = parseInt(item.actionValue);
        switch (item.actionType) {
          case 1:
            item.actionMin = 1;
            item.actionMax = 900;
            break;
          case 2:
            item.actionMin = -180;
            item.actionMax = 180;
            break;
          case 3:
            item.actionMin = -120;
            item.actionMax = 45;
            break;
          case 7:
            item.actionMin = 2;
            item.actionMax = 200;
            break;
          case 10:
            item.actionMin = 1;
            item.actionMax = 30;
            break;
        }
      });
    }
    ruleForm.addReachTargetPointActions = data.getReachTargetPointActions
      ? data.getReachTargetPointActions
      : [];
    actionItems.value = data.getReachTargetPointActions
      ? data.getReachTargetPointActions
      : [];
  } catch (err) {
    ElMessage.error('加载数据失败');
  }
};

onMounted(() => {
  getAlarm();
});
</script>

<template>
  <div class="p-2">
    <div class="content" style="position: relative">
      <ElTabs v-model="activeName" class="demo-tabs">
        <ElTabPane label="接警配置" name="first">
          <div class="page">
            <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="170px" label-position="left"
              style="margin-top: 20px">
              <ElFormItem label="默认飞行高度（m）：" prop="defaultFlyHeight">
                <ElInputNumber v-model="ruleForm.defaultFlyHeight" placeholder="请输入默认飞行高度（m）" style="width: 300px"
                  controls-position="right" />
              </ElFormItem>
              <ElFormItem label="默认飞行速度（m/s）：" prop="defaultFlySpeed">
                <ElInputNumber v-model="ruleForm.defaultFlySpeed" placeholder="请输入默认飞行速度（m/s）" style="width: 300px"
                  controls-position="right" />
              </ElFormItem>
              <ElFormItem label="默认返航高度（m）：" prop="defaultTurnBackHeight">
                <ElInputNumber v-model="ruleForm.defaultTurnBackHeight" placeholder="请输入默认返航高度（m）" style="width: 300px"
                  controls-position="right" />
              </ElFormItem>
              <ElFormItem label="是否自动出警：" prop="autoTreatTheCasesStatus">
                <ElRadioGroup v-model="ruleForm.autoTreatTheCasesStatus">
                  <ElRadio value="1">是</ElRadio>
                  <ElRadio value="2">否</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
              <ElFormItem label="警情失效时长（h）：" prop="warningInstanceExpire">
                <ElInputNumber v-model="ruleForm.warningInstanceExpire" placeholder="请输入警情失效时长（h）" style="width: 300px"
                  controls-position="right" />
              </ElFormItem>
              <ElFormItem label="抵达目标点动作：">
                <div style="display: flex; flex-direction: column">
                  <div class="right">
                    <ElButton link @click="addAction()" class="add" style="margin-top: 6px">
                      <ElIcon class="icon">
                        <Plus />
                      </ElIcon>
                      添加动作
                    </ElButton>
                  </div>
                </div>
              </ElFormItem>
            </ElForm>
            <div class="action-list">
              <ul v-if="actionItems.length > 0">
                <li v-for="(item, index) in actionItems" :key="index" class="action-item">
                  <div style="display: flex; flex-direction: column; width: 100%">
                    <div style="
                        display: flex;
                        justify-content: space-between;
                        width: 100%;
                      ">
                      <div class="actionName">{{ item.name }}</div>
                      <div class="rightLi">
                        <div class="valElSlider" v-if="
                          item.actionType == 1 ||
                          item.actionType == 2 ||
                          item.actionType == 3 ||
                          item.actionType == 7 ||
                          item.actionType == 9 ||
                          item.actionType == 10
                        ">
                          <ElInput class="inputNumber" v-model.number="item.actionValue"
                            style="width: 56px; height: 20px" @change="changeValue(item)"></ElInput>
                          <span v-if="item.actionType == 2 || item.actionType == 3" class="du">°</span>
                          <span v-if="
                            item.actionType == 1 ||
                            item.actionType == 9 ||
                            item.actionType == 10
                          " class="other">S</span>
                          <span v-if="item.actionType == 7" class="other">X</span>
                        </div>
                        <ElButton text circle @click="removeAction(index)" class="delete-btn">
                          <ElIcon color="#272636">
                            <Delete />
                          </ElIcon>
                        </ElButton>
                      </div>
                    </div>
                    <div style="
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        width: 100%;
                      " v-if="
                        item.actionType == 1 ||
                        item.actionType == 2 ||
                        item.actionType == 3 ||
                        item.actionType == 7 ||
                        item.actionType == 9 ||
                        item.actionType == 10
                      ">
                      <img class="circle" style="margin-right: 8px" src="/static/del.png" @click="del(item)"
                        alt="" />
                      <ElSlider :min="item.actionMin" :max="item.actionMax" v-model="item.actionValue" size="small" />
                      <img class="circle" style="margin-left: 8px" src="/static/add.png" @click="add(item)"
                        alt="" />
                    </div>
                  </div>
                </li>
              </ul>
              <div v-else class="empty-tip">暂无动作</div>
            </div>
            <div class="buts">
              <ElDivider />
              <ElButton type="primary" @click="debouncedSubmitForm">
                保存配置
              </ElButton>
            </div>
          </div>
        </ElTabPane>
      </ElTabs>
    </div>
    <!-- 配置项 -->
    <ElDialog v-model="dialogVisible" title="选择动作" width="200">
      <div class="list">
        <ElMenu background-color="#fff" text-color="black" active-text-color="#ffd04b">
          <ElMenuItem @click="selectAction(item)" v-for="item in settingList" :key="item.actionType">{{ item.name }}
          </ElMenuItem>
        </ElMenu>
      </div>
    </ElDialog>
  </div>
</template>
<style scoped>
.content {
  min-height: calc(100vh - 106px);
  padding: 20px;
  background: #fff;
}

h1 {
  margin-bottom: 20px;
  font-weight: 900;
}

.buts {
  margin-top: 50px;
  text-align: center;
}

:deep(.el-tabs__item) {
  font-size: 18px !important;
}

.add {
  color: var(--el-color-primary);
}

.right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 300px;
}

.action-list {
  width: 450px;
  min-height: 100px;
  margin-top: 10px;
}

.action-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.action-item:hover {
  background-color: var(--el-fill-color);
}

.actionName {
  font-size: 14px;
  line-height: 32px;
}

.empty-tip {
  padding: 20px 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  text-align: center;
}

.add {
  margin-bottom: 10px;
}

.icon {
  margin-right: 4px;
}

.rightLi {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  line-height: 20px;
  color: #303133;
  text-align: center;
}

.valElSlider {
  position: relative;
  width: 56px;
  height: 20px;
  background: #e4e7ed;
  border-radius: 2px;
}

.du {
  position: absolute;
  top: -8px;
  right: -10px;
}

.other {
  position: absolute;
  top: 0;
  right: -14px;
}

.delete-btn {
  padding: 0;
  margin-left: 18px;
}

.el-slider--small {
  margin-left: 10px;
}

:deep(.el-button.is-circle) {
  width: auto !important;
}

:deep(.el-slider__bar) {
  background: linear-gradient(79deg, #00ccd0 0%, #3a6af0 100%);
  border-radius: 6px;
  box-shadow: 0 0 8px 0 rgb(97 137 202 / 43%);
}

:deep(.el-slider__button) {
  width: 12px;
  height: 12px;
  background: #fff;
  border: none;
  box-shadow: 0 0 8px 0 rgb(97 137 202 / 43%);
}

.circle {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

:deep(.el-menu) {
  border: none;
}

.el-menu-item {
  height: 36px;
  line-height: 36px;
}

.el-menu--horizontal {
  --el-menu-horizontal-height: 100px;
}

.valElSlider :deep(.el-input__wrapper) {
  height: 20px !important;
  line-height: 20px !important;
  background: #e4e7ed;
  border: none;
  border-radius: 2px;
}
</style>
